package com.my.study.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.my.study.properties.AmazonS3Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: yidujun
 * @create: 2021/09/15 20:23
 */
@Configuration
@EnableConfigurationProperties(AmazonS3Properties.class)
public class AmazonS3AutoConfig {

    private AmazonS3Properties amazonS3Properties;

    @Autowired
    public void setAmazonS3Properties(AmazonS3Properties amazonS3Properties) {
        this.amazonS3Properties = amazonS3Properties;
    }

    @Bean
    public AmazonS3 amazonS3() {
        // init BasicAWSCredentials
        BasicAWSCredentials credentials =
                new BasicAWSCredentials(amazonS3Properties.getAccessKey(), amazonS3Properties.getSecretKey());

        // init configuration, set protocol is HTTP
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setProtocol(Protocol.HTTP);
        configuration.setSignerOverride("S3SignerType");

        // init endpoint configuration
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(
                "http://" + amazonS3Properties.getEndpoint(), Regions.CN_NORTH_1.getName());

        // create AmazonS3 by using AmazonS3ClientBuilder
        return AmazonS3ClientBuilder.standard()
                .withClientConfiguration(configuration)
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                // 允许使用DNS地址
                .enablePathStyleAccess()
                .build();
    }
}
